<template>
  <div class="wang-editor-container">
    <Toolbar class="wang-editor-toolbar" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor class="wang-editor-content" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
      @onCreated="handleCreated" @onChange="handleChange" @onDestroyed="handleDestroyed" />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: [String, Number],
    default: 400
  },
  placeholder: {
    type: String,
    default: '请输入内容...'
  },
  mode: {
    type: String,
    default: 'default', // 或 'simple'
    validator: (value) => ['default', 'simple'].includes(value)
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'change'])

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')

// 模拟 v-model
watch(() => props.modelValue, (newVal) => {
  valueHtml.value = newVal
}, { immediate: true })

watch(valueHtml, (newVal) => {
  emit('update:modelValue', newVal)
})

// 工具栏配置
const toolbarConfig = {
  excludeKeys: [
    'group-video', // 排除视频
    'fullScreen' // 排除全屏
  ]
}

// 编辑器配置
const editorConfig = {
  placeholder: props.placeholder,
  readOnly: props.disabled,
  MENU_CONF: {
    // 配置上传图片
    uploadImage: {
      server: process.env.NODE_ENV === 'development' ? '/api/api/common/upload' : '/api/common/upload',
      fieldName: 'file',
      metaWithUrl: false,
      headers: {
        Accept: 'text/x-json',
        otherKey: 'xxx'
      },
      maxFileSize: 1 * 1024 * 1024, // 1M
      base64LimitSize: 5 * 1024, // 5kb
      onBeforeUpload(file) {

        return file
      },
      onProgress(progress) {

      },
      onSuccess(file, res) {

        if (res.status && res.name) {

        }
      },
      onFailed(file, res) {
        console.error('图片上传失败 - onFailed', file, res)
        // 可以在这里显示错误提示
      },
      onError(file, err, res) {
        console.error('图片上传错误 - onError', file, err, res)
        // 可以在这里显示错误提示
      },
      customInsert(res, insertFn) {
        // res 即服务端的返回结果


        // 根据实际返回格式处理图片URL
        if (res.status && res.name) {
          // 处理图片URL，确保是完整的URL
          let imageUrl = res.name

          // 如果URL以//开头，添加协议
          if (imageUrl.startsWith('//')) {
            imageUrl = 'https:' + imageUrl
          }
          // 如果URL不是完整URL，添加域名前缀
          else if (!imageUrl.startsWith('http')) {
            imageUrl = 'https:' + imageUrl
          }



          // 插入图片到编辑器
          insertFn(imageUrl, '', '')
        } else {
          console.error('图片上传失败或返回格式错误:', res)
        }
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const handleChange = (editor) => {
  emit('change', editor.getHtml())
}

const handleDestroyed = () => {
  editorRef.value = null
}

// 暴露编辑器实例方法
defineExpose({
  getEditor: () => editorRef.value
})
</script>

<style scoped>
.wang-editor-container {
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}

.wang-editor-toolbar {
  border-bottom: 1px solid #ccc;
}

.wang-editor-content {
  height: v-bind('props.height + "px"');
  overflow-y: hidden;
}

/* 编辑器内容区域样式 */
.wang-editor-container :deep(.w-e-text-container) {
  background-color: #fff;
  height: 200px;
}

.wang-editor-container :deep(.w-e-text-placeholder) {
  color: #999;
  font-style: normal;
}

/* 工具栏样式 */
.wang-editor-container :deep(.w-e-toolbar) {
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.wang-editor-container :deep(.w-e-toolbar .w-e-bar-item button) {
  color: #595959;
}

.wang-editor-container :deep(.w-e-toolbar .w-e-bar-item button:hover) {
  color: #1890ff;
  background-color: #f0f0f0;
}

/* 禁用状态样式 */
.wang-editor-container.disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.wang-editor-container.disabled :deep(.w-e-text-container) {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.wang-editor-container.disabled :deep(.w-e-toolbar) {
  background-color: #f5f5f5;
  pointer-events: none;
}
</style>
